/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bifang.gwt.server.action.stat;


import han.bifang.gwt.client.common.entity.NormalizedMessage;

import org.apache.xmlbeans.XmlObject;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import v1.message.bashe.han.BasheMessageDocument;
import v1.message.bashe.han.BasheMessageDocument.BasheMessage.Body;
import v1.message.bashe.han.BasheMessageDocument.BasheMessage.Heads;
import v1.message.bashe.han.HeadDocument.Head;

/**
 * @Author Kent
 */
public class InternalConverter {
	
	public static BasheMessageDocument normailzed2Bashe(NormalizedMessage msg)throws Exception{
		BasheMessageDocument doc = BasheMessageDocument.Factory.newInstance();
		Body body = doc.addNewBasheMessage().addNewBody();
		Heads heads = doc.getBasheMessage().addNewHeads();
		for(String head : msg.getHeads().keySet()){
			Head h = heads.addNewHead();
			h.setName(head);
			h.setValue(msg.getHead(head));
		}
		XmlObject o = XmlObject.Factory.parse(msg.getBody());
		body.set(o);
		return doc;
	}
	
	public static NormalizedMessage bashe2Normalized(BasheMessageDocument doc )throws Exception{
		NormalizedMessage msg = new NormalizedMessage();
		Body body = doc.getBasheMessage().getBody();
		Heads heads = doc.getBasheMessage().getHeads();
		for(Head h : heads.getHeadList()){
			msg.setHead(h.getName(), h.getValue());
		}
		
		NodeList nl = body.newDomNode().getChildNodes();
		Node tmp = null;
		for (int i = 0; i < nl.getLength(); i++) {
			if (nl.item(i).getLocalName() != null) {
				// && nl.item(i).getLocalName().equals("service")) {
				tmp = nl.item(i);
				break;
			}
		}
		nl = tmp.getChildNodes();
		for (int i = 0; i < nl.getLength(); i++) {
			if (nl.item(i).getLocalName() != null) {
				tmp = nl.item(i);
				break;
			}
		}
		XmlObject bodyDoc = XmlObject.Factory.parse(tmp);
		msg.setBody(bodyDoc.toString());
		return msg;
	}

}
